package u.can.i.up.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;

public class FileUtil {

	public static List<File> getAllFileList(String path) {
		List<File> files = new ArrayList<File>();
		SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				files.add(file.toFile());
				return super.visitFile(file, attrs);
			}
		};
		try {
			Files.walkFileTree(Paths.get(path), finder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return files;
	}

	public static List<String> getAllPathList(String path) {
		List<String> paths = new ArrayList<String>();
		SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				paths.add(file.toFile().getAbsolutePath());
				return super.visitFile(file, attrs);
			}
		};
		try {
			Files.walkFileTree(Paths.get(path), finder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return paths;
	}

	public static String getMD5byPath(String path) {
		File file = new File(path);
		Long length = file.length();
		BufferedInputStream bis = null;
		String md5 = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			byte[] content = new byte[length.intValue()];
			bis.read(content);
			md5 = DigestUtils.md5Hex(content).toUpperCase();
			bis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return md5;
	}
}
